package com.czc.weather.push.weather.service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Service
public class WeathernfoService {

    @Value("${hefeng.weather.apiKey}")
    private String apiKey;

    // 调用和风天气api获取24小时天气数据
    public JSONObject getWeatherInfo(String code) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(5, TimeUnit.SECONDS) // 连接超时时间
            .readTimeout(5, TimeUnit.SECONDS)    // 读取超时时间
            .writeTimeout(5, TimeUnit.SECONDS)   // 写入超时时间
            .build();
        Request request = null;
        Response response = null;
        String url = "https://devapi.qweather.com/v7/weather/24h?location=" + code;
        request = new Request.Builder()
                .url(url)
                .header("X-QW-Api-Key", apiKey)
                .get()
                .build();
        response = client.newCall(request).execute();
        
        if (response.isSuccessful() && response.body() != null) {
            String responseBody = response.body().string();
            return JSONObject.parseObject(responseBody);
        } else {
            throw new IOException("请求天气信息失败，状态码: " + response.code());
        }
    }

    // 通过地名获取地区编码
    public String getAreaCode(String areaName) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
        .connectTimeout(5, TimeUnit.SECONDS) // 连接超时时间
        .readTimeout(5, TimeUnit.SECONDS)    // 读取超时时间
        .writeTimeout(5, TimeUnit.SECONDS)   // 写入超时时间
        .build();
        Request request = null;
        Response response = null;
        request = new Request.Builder()
                .url("https://geoapi.qweather.com/v2/city/lookup?location=" + areaName)
                .header("X-QW-Api-Key", apiKey)
                .get()
                .build();
        response = client.newCall(request).execute();

        // 检查响应是否成功
        if (response.isSuccessful() && response.body() != null) {
            String responseBody = response.body().string();
            JSONObject jsonResponse = JSON.parseObject(responseBody);

            // 检查返回的 code 是否为 200
            if ("200".equals(jsonResponse.getString("code"))) {
                JSONObject location = jsonResponse.getJSONArray("location").getJSONObject(0);
                return location.getString("id"); // 返回 location 中的 id
            }
        }
        return null; // 如果没有找到或请求失败，返回 null
    }
}